#!/usr/bin/env python
import sys, os
import pygtk, gtk
import gtk.glade
import gtksourceview2
from HollyWidgets.TreeViewBased.TreeView import HTreeView, HTreeNode

class HExplorerWidget( HTreeView.HTreeView ):

	def __init__(self):
		HTreeView.HTreeView.__init__(self)
		self.NodeIconVisible( True )
		#
		self.BasePath   = "/"
		theme           = gtk.icon_theme_get_default()
		self.FolderIcon = theme.load_icon( "folder"   , 16, gtk.ICON_LOOKUP_FORCE_SVG )
		self.FileIcon   = theme.load_icon( "python"   , 16, gtk.ICON_LOOKUP_FORCE_SVG )
		self.Events["BeforeNodeExpand"] = self.OnBeforeNodeExpand
		self.refresh_list()
	
	def OnBeforeNodeExpand( self, widget, args ):
                path          = self.GetPathFromNode( args.Node )
                self.buildNode ( args.Node )
                #select the expanded node
                self.selectNode( args.Node )
	
	def GetPathFromNode( self, node ):
		ret       = node.get_text()
                parent    = node.ParentNode
                while ( parent != None ) :
                        ret    = parent.get_text() + "/" + ret
                        parent = parent.ParentNode
                ret       = "/" + ret.replace( "//", "/" );
                return ret
                
	def buildNode( self, node ):
		path          =  self.GetPathFromNode(node)
                try:
	                node.Nodes.Clear()
			#citeste folderele din directorul base
			
			for f in os.listdir( path ):
				if os.path.isdir( os.path.join( path, f ) ):
					new_node = HTreeNode.HTreeNode(  f, False, self.FolderIcon, self.FolderIcon )
					dummy    = HTreeNode.HTreeNode(  f, False )
					node.Nodes.Add( new_node  )
					new_node.Nodes.Add( dummy )
			#citeste fisierele din directorul curent
			for f in os.listdir( path ):
				if os.path.isfile( os.path.join( path, f ) ):
					new_node  = HTreeNode.HTreeNode(  f, False, self.FileIcon, self.FileIcon )
					node.Nodes.Add( new_node  )
                except:
                        node.Nodes.Clear();
                        print "Cannot acces folder!"


	
	def set_base_path( self, path ):
		self.BasePath = path
	
	def refresh_list( self ):
		path = self.BasePath
		self.Nodes.Clear()
		#citeste folderele din directorul base
		for f in os.listdir( path ):
			if os.path.isdir( os.path.join( path, f ) ):
				node  = HTreeNode.HTreeNode(  f, False, self.FolderIcon, self.FolderIcon )
				dummy = HTreeNode.HTreeNode(  "dummy", False )
				self.Nodes.Add( node  )
				node.Nodes.Add( dummy )
		#citeste fisierele din directorul curent
		for f in os.listdir( path ):
			if os.path.isfile( os.path.join( path, f ) ):
				node  = HTreeNode.HTreeNode(  f, False, self.FileIcon, self.FileIcon )
				self.Nodes.Add( node  )
